'use strict';

const Controller = require("./base");
class HomeController extends Controller {
  async index() {
    const { ctx } = this;
    ctx.body = 'hi, egg';
  }

  async create() {
    const { ctx } = this; 
    const result = await ctx.service.generic.create(ctx.query.tableName,ctx.request.body);
    ctx.body = result;
  }
   async update() {
    const { ctx } = this;
    const { tableName, id } = ctx.query; 
    const result = await ctx.service.generic.update(tableName, ctx.request.body);
    ctx.body = result;
  }
   async delete() {
    const { ctx } = this;
    const { tableName, id } = ctx.query;
    await ctx.service.generic.delete(tableName, id);
    ctx.status = 204;
  }
   async findById() {
    const { ctx } = this;
    const { tableName, id } = ctx.query;
    const result = await ctx.service.generic.findById(tableName, id);
    ctx.body = result;
  }
  async findAll() {
    const { ctx } = this; 
    const { tableName,page, perPage } = ctx.query;
    const result = await ctx.service.generic.findAll(tableName,{}, page, perPage);
    ctx.body = result;
  }

  // 通用的模糊分页查询排序语句 后期处理安全与权限问题
  async search() {
    const { ctx } = this;
    const { tableName, page = 1, perPage = 10 } = ctx.query;
    const { query,order} = ctx.request.body
    const results = await this.app.mysql.query(`select * from ${tableName} ${this.getWhere({ query })} ${order?order:''} limit ${(page - 1) * perPage},${perPage}`);
    this.success(results); 
  }
}

module.exports = HomeController;
